﻿/*
* 创建者：LIYINFAI
* 创建时间：2023/12/22 11:40:00
* 描述：
* --------------------------------------
* 修改说明：
* --------------------------------------
*/
using CommonLibrary.Forms;
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Windows.Forms;

namespace CommonLibrary
{
    /// <summary>
    /// 多码扫码管理窗体
    /// </summary>
    public partial class FormScan : HWFrmWithTitle
    {
        private bool mIsFirstTimeSelected = true;
        private int mTcpLastSelectedRowIndex = -1;
        private int mSerialLastSelectedRowIndex = -1;
        /// <summary>
        /// 构造函数
        /// </summary>
        public FormScan()
        {
            InitializeComponent();
        }
        private void FormScan_Load(object sender, EventArgs e)
        {
            InitColumns();
            LoadConfig();
        }
        private void LoadConfig()
        {
            this.mIsFirstTimeSelected = true;
            this.mSerialLastSelectedRowIndex = -1;
            this.mTcpLastSelectedRowIndex = -1;
            this.dataGridViewSerial.Rows.Clear();
            this.dataGridViewTcp.Rows.Clear();
            this.dataGridViewModules.Rows.Clear();


            var businessConfig = BusinessConfig.Instance();
            this.textBoxRepeatTimes.Text = businessConfig.ScanRepeatTimes.ToString();
            this.textBoxTimeout.Text = businessConfig.ScanTimeout.ToString();
            this.textBoxBarcodeLength.Text = businessConfig.BarcodeLength.ToString();
            this.checkBoxIsCheckLength.Checked = businessConfig.IsCheckBarcodeLength;
            this.textBoxBarcodePrev.Text = businessConfig.BarcodePrev.ToString();
            this.checkBoxCheckBarcodePrev.Checked = businessConfig.IsCheckBarcodePrev;


            var tcps = ScanHelper.GetAutoScanTCPConfig();
            var coms = ScanHelper.GetAutoScanComConfig();

            if (tcps != null && tcps.Count > 0)
            {
                this.dataGridViewTcp.Rows.Clear();

                foreach (var t in tcps)
                {
                    var index = this.dataGridViewTcp.Rows.Add(1);
                    DataGridViewRow newRow = this.dataGridViewTcp.Rows[index];
                    newRow.Cells["Name"].Value = t.Remark;
                    newRow.Cells["TcpIP"].Value = t.ServerIP;
                    newRow.Cells["TcpPort"].Value = t.ServerPort;
                    newRow.Cells["Cmd"].Value = t.CommandText;
                    newRow.Tag = t;
                }
            }
            if (coms != null && coms.Count > 0)
            {
                this.dataGridViewSerial.Rows.Clear();

                foreach (var r in coms)
                {
                    var index = this.dataGridViewSerial.Rows.Add(1);
                    DataGridViewRow newRow = this.dataGridViewSerial.Rows[index];
                    newRow.Cells["Name"].Value = r.Remark;
                    newRow.Cells["PortName"].Value = !string.IsNullOrWhiteSpace(r.PortName) && PortNames.Contains(r.PortName) ? r.PortName : PortNames[0];
                    newRow.Cells["Parity"].Value = r.Parity.ToString();
                    newRow.Cells["DataBit"].Value = r.DataBits.ToString();
                    newRow.Cells["StopBit"].Value = r.StopBits.ToString();
                    newRow.Cells["BaudRate"].Value = r.BaudRate.ToString();
                    newRow.Cells["Cmd"].Value = r.CommandText;
                    newRow.Tag = r;
                }
            }

            this.dataGridViewTcp.Rows[0].Cells[0].Selected = true;
        }
        private string[] PortNames = SerialPort.GetPortNames();

        DataGridViewComboBoxColumn portNameRtuColumn = new DataGridViewComboBoxColumn();
        DataGridViewComboBoxColumn baudRateRtuColumn = new DataGridViewComboBoxColumn();
        DataGridViewComboBoxColumn parityRtuColumn = new DataGridViewComboBoxColumn();
        DataGridViewComboBoxColumn dataBitRtuColumn = new DataGridViewComboBoxColumn();
        DataGridViewComboBoxColumn stopBitRtuColumn = new DataGridViewComboBoxColumn();


        private void InitColumns()
        {
            CommonHelper.CreateTextGridColumn(this.dataGridViewTcp, "Name", "名称");
            CommonHelper.CreateTextGridColumn(this.dataGridViewTcp, "TcpIP", "IP");
            CommonHelper.CreateTextGridColumn(this.dataGridViewTcp, "TcpPort", "端口");
            CommonHelper.CreateTextGridColumn(this.dataGridViewTcp, "Cmd", "扫码命令");
            this.dataGridViewTcp.DoubleBufferedDataGirdView(true);
            this.dataGridViewTcp.InitStyle();

            CommonHelper.InitComboGridColumn(portNameRtuColumn, "PortName", "串口", PortNames);
            CommonHelper.InitComboGridColumn(baudRateRtuColumn, "BaudRate", "波特率", new string[] { "2400", "4800", "9600", "14400", "19200", "115200" });
            CommonHelper.InitComboGridColumn(parityRtuColumn, "Parity", "校验位", new string[] { "0", "1", "2", "3", "4" });
            CommonHelper.InitComboGridColumn(dataBitRtuColumn, "DataBit", "数据位", new string[] { "5", "6", "7", "8" });
            CommonHelper.InitComboGridColumn(stopBitRtuColumn, "StopBit", "停止位", new string[] { "0", "1", "2", "3" });

            CommonHelper.CreateTextGridColumn(this.dataGridViewSerial, "Name", "名称");
            this.dataGridViewSerial.Columns.Add(portNameRtuColumn);
            this.dataGridViewSerial.Columns.Add(baudRateRtuColumn);
            this.dataGridViewSerial.Columns.Add(parityRtuColumn);
            this.dataGridViewSerial.Columns.Add(dataBitRtuColumn);
            this.dataGridViewSerial.Columns.Add(stopBitRtuColumn);
            CommonHelper.CreateTextGridColumn(this.dataGridViewSerial, "Cmd", "扫码命令");
            this.dataGridViewSerial.DoubleBufferedDataGirdView(true);
            this.dataGridViewSerial.InitStyle();

            CommonHelper.CreateTextGridColumn(this.dataGridViewModules, "Trigger", "触发地址");
            CommonHelper.CreateTextGridColumn(this.dataGridViewModules, "Barcode", "条码地址");
            CommonHelper.CreateTextGridColumn(this.dataGridViewModules, "Time", "扫码时间地址");
            CommonHelper.CreateTextGridColumn(this.dataGridViewModules, "Result", "扫码结果地址");
            CommonHelper.CreateTextGridColumn(this.dataGridViewModules, "Done", "扫码完成地址");
            CommonHelper.CreateTextGridColumn(this.dataGridViewModules, "Mes", "MES反馈地址");
            CommonHelper.CreateTextGridColumn(this.dataGridViewModules, "Remark", "备注");
            this.dataGridViewModules.DoubleBufferedDataGirdView(true);
            this.dataGridViewModules.InitStyle();
        }

        private void buttonSave_Click(object sender, EventArgs e)
        {
            CommonHelper.ShowWaiting(this, "数据保存中，请稍候......");

            if (GlobalStatus.APP == EAppStatus.RUN)
            {
                HWMessageBox.Show(this, "设备运行中，不允许修改参数");
                CommonHelper.CloseWaiting();
                return;
            }
            try
            {
                SaveModules();
                #region tcp
                bool isValidTcp = true, isValidCom = true, isValidOther = true;
                int timeout = 1000, repeatTimes = 3, barodeLength = 40;
                bool isCheckBarcodePrev = false, isCheckBarcodeLength = false;
                string barcodePrev = string.Empty;
                List<ScanTcpParam> tcpList = new List<ScanTcpParam>();
                List<ScanComParam> comList = new List<ScanComParam>();

                if (this.dataGridViewTcp.Rows != null && this.dataGridViewTcp.Rows.Count > 0)
                {
                    int rowIndex = 0;
                    foreach (DataGridViewRow row in this.dataGridViewTcp.Rows)
                    {
                        var name = CommonHelper.GetCellStringValue(row, "Name");
                        if (!string.IsNullOrWhiteSpace(name))
                        {
                            if (tcpList.Find(v => v.Remark.Equals(name)) != null)
                            {
                                HWMessageBox.Show(this, $"第{(rowIndex + 1)}行的名称有重复");
                                break;
                            }
                            var ip = CommonHelper.GetCellStringValue(row, "TcpIP");
                            var port = CommonHelper.GetCellStringValue(row, "TcpPort");
                            var cmd = CommonHelper.GetCellStringValue(row, "Cmd");

                            IPAddress ipValue = null;
                            if (!IPAddress.TryParse(ip, out ipValue))
                            {
                                HWMessageBox.Show(this, $"第{(rowIndex + 1)}行的IP有误");
                                isValidTcp = false;
                                break;
                            }
                            int portValue = 502;
                            if (!int.TryParse(port, out portValue))
                            {
                                HWMessageBox.Show(this, $"第{(rowIndex + 1)}行的端口有误");
                                isValidTcp = false;
                                break;
                            }
                            if (string.IsNullOrWhiteSpace(cmd))
                            {
                                HWMessageBox.Show(this, $"第{(rowIndex + 1)}行的命令有误");
                                isValidTcp = false;
                                break;
                            }
                            cmd = cmd.Replace("\\r", "\r").Replace("\\n", "\n");

                            List<ScanPLCEntity> tcpPLCEntities = new List<ScanPLCEntity>();
                            if (row.Tag != null && row.Tag is ScanTcpParam)
                            {
                                tcpPLCEntities = (row.Tag as ScanTcpParam).PLCEntities;
                            }
                            tcpList.Add(new ScanTcpParam()
                            {
                                Command = cmd,
                                Remark = name,
                                ServerIP = ip,
                                ServerPort = portValue,
                                PLCEntities = tcpPLCEntities
                            });
                        }
                        rowIndex++;
                    }
                }
                #endregion
                if (isValidTcp)
                {
                    if (this.dataGridViewSerial.Rows != null && this.dataGridViewSerial.Rows.Count > 0)
                    {
                        int rowIndex = 0;
                        foreach (DataGridViewRow row in this.dataGridViewSerial.Rows)
                        {
                            var name = CommonHelper.GetCellStringValue(row, "Name");
                            if (!string.IsNullOrWhiteSpace(name))
                            {
                                if (comList.Find(v => v.Remark.Equals(name)) != null)
                                {
                                    HWMessageBox.Show(this, $"第{(rowIndex + 1)}行的名称有重复");
                                    break;
                                }
                                var portName = CommonHelper.GetCellStringValue(row, "PortName");
                                var baudRate = CommonHelper.GetCellStringValue(row, "BaudRate");
                                var parity = CommonHelper.GetCellStringValue(row, "Parity");
                                var dataBit = CommonHelper.GetCellStringValue(row, "DataBit");
                                var stopBit = CommonHelper.GetCellStringValue(row, "StopBit");
                                var cmd = CommonHelper.GetCellStringValue(row, "Cmd");

                                if (string.IsNullOrWhiteSpace(portName))
                                {
                                    HWMessageBox.Show(this, $"第{(rowIndex + 1)}行的串口有误");
                                    isValidCom = false;
                                    break;
                                }
                                if (string.IsNullOrWhiteSpace(cmd))
                                {
                                    HWMessageBox.Show(this, $"第{(rowIndex + 1)}行的命令有误");
                                    isValidTcp = false;
                                    break;
                                }
                                cmd = cmd.Replace("\\r", "\r").Replace("\\n", "\n");

                                int baudRateValue = int.Parse(baudRate);
                                int parityValue = int.Parse(parity);
                                int dataBitValue = int.Parse(dataBit);
                                int stopBitValue = int.Parse(stopBit);


                                List<ScanPLCEntity> comPLCEntities = new List<ScanPLCEntity>();
                                if (row.Tag != null && row.Tag is ScanComParam)
                                {
                                    comPLCEntities = (row.Tag as ScanComParam).PLCEntities;
                                }


                                comList.Add(new ScanComParam()
                                {
                                    Command = cmd,
                                    BaudRate = baudRateValue,
                                    Parity = parityValue,
                                    DataBits = dataBitValue,
                                    PortName = portName,
                                    Remark = name,
                                    StopBits = stopBitValue,
                                    PLCEntities = comPLCEntities,
                                });
                            }
                            rowIndex++;
                        }
                    }
                }

                if (isValidTcp && isValidCom)
                {
                    if (!int.TryParse(this.textBoxTimeout.Text, out timeout) || !int.TryParse(this.textBoxRepeatTimes.Text, out repeatTimes))
                    {
                        isValidOther = false;

                        HWMessageBox.Show(this, "超时时间或重复次数有误");
                    }
                    else if (!int.TryParse(this.textBoxBarcodeLength.Text, out barodeLength))
                    {
                        isValidOther = false;

                        HWMessageBox.Show(this, "条码长度相关有误");
                    }
                    else if (this.checkBoxCheckBarcodePrev.Checked && string.IsNullOrWhiteSpace(this.textBoxBarcodePrev.Text))
                    {
                        isValidOther = false;

                        HWMessageBox.Show(this, "条码前缀相关有误");
                    }
                    else
                    {
                        isCheckBarcodePrev = this.checkBoxCheckBarcodePrev.Checked;
                        isCheckBarcodeLength = this.checkBoxIsCheckLength.Checked;
                        barcodePrev = this.textBoxBarcodePrev.Text;
                    }
                }
                if (isValidTcp && isValidCom && isValidOther)
                {
                    ScanHelper.SaveAutoScanTCPConfig(tcpList);
                    ScanHelper.SaveAutoScanComConfig(comList);

                    var otherConfig = BusinessConfig.Instance();
                    otherConfig.ScanRepeatTimes = repeatTimes;
                    otherConfig.ScanTimeout = timeout;
                    otherConfig.BarcodeLength = barodeLength;
                    otherConfig.IsCheckBarcodeLength = isCheckBarcodeLength;
                    otherConfig.IsCheckBarcodePrev = isCheckBarcodePrev;
                    otherConfig.BarcodePrev = barcodePrev;
                    otherConfig.Save();
                    LogHelper.Info($"修改Scan配置\r\n{CommonHelper.GetJsonString(otherConfig)}\r\n{CommonHelper.GetJsonString(tcpList)}\r\n{CommonHelper.GetJsonString(comList)}");
                    APPInstance.ResetHelpers();
                    this.DialogResult = DialogResult.OK;
                    HWMessageBox.Show(this, "保存成功");
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex);
                HWMessageBox.Show(this, $"发生异常：{ex.Message}");
            }
            CommonHelper.CloseWaiting();
        }

        private void dataGridViewCom_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex.Equals(this.dataGridViewSerial.Columns.IndexOf(portNameRtuColumn))
                || e.ColumnIndex.Equals(this.dataGridViewSerial.Columns.IndexOf(parityRtuColumn))
                || e.ColumnIndex.Equals(this.dataGridViewSerial.Columns.IndexOf(baudRateRtuColumn))
                || e.ColumnIndex.Equals(this.dataGridViewSerial.Columns.IndexOf(dataBitRtuColumn))
                || e.ColumnIndex.Equals(this.dataGridViewSerial.Columns.IndexOf(stopBitRtuColumn)))
            {
                SendKeys.Send("{F4}");
            }
        }

        private void dataGridViewCom_DefaultValuesNeeded(object sender, DataGridViewRowEventArgs e)
        {
            var portNameCell = e.Row.Cells["PortName"] as DataGridViewComboBoxCell;
            if (portNameCell != null && PortNames != null && PortNames.Length > 0)
            {
                portNameCell.Value = PortNames[0];
            }
            var baudRateCell = e.Row.Cells["BaudRate"] as DataGridViewComboBoxCell;
            if (baudRateCell != null)
            {
                baudRateCell.Value = "9600";
            }
            var parityCell = e.Row.Cells["Parity"] as DataGridViewComboBoxCell;
            if (parityCell != null)
            {
                parityCell.Value = "0";
            }
            var stopBitCell = e.Row.Cells["StopBit"] as DataGridViewComboBoxCell;
            if (stopBitCell != null)
            {
                stopBitCell.Value = "1";
            }
            var dataBitCell = e.Row.Cells["DataBit"] as DataGridViewComboBoxCell;
            if (dataBitCell != null)
            {
                dataBitCell.Value = "8";
            }
        }

        private void toolStripMenuItemTcpRead_Click(object sender, EventArgs e)
        {
            CommonHelper.ShowWaiting(this, "功能触发中，请稍候......");
            var cells = this.dataGridViewTcp.SelectedCells;
            if (cells != null && cells.Count > 0)
            {
                var row = this.dataGridViewTcp.Rows[cells[0].RowIndex];
                var tag = row.Tag as ScanTcpParam;
                if (tag != null)
                {
                    var name = tag.Remark;
                    if (!string.IsNullOrWhiteSpace(name))
                    {
                        var ip = tag.ServerIP;
                        var port = tag.ServerPort;
                        var cmd = tag.Command;
                        cmd = cmd.Replace("\\r", "\r").Replace("\\n", "\n");

                        if (string.IsNullOrWhiteSpace(cmd))
                        {
                            HWMessageBox.Show(this, "扫码命令有误");
                        }
                        else
                        {
                            string cmdValue = cmd.Replace("\\r", "\r").Replace("\\n", "\n");

                            var helper = APPInstance.HELPERS != null ?
                                APPInstance.HELPERS.Find(v => v is ScanHelper && v.Name.Equals(name)
                                && v.CommunicationType == ECommunicationType.TCP && v.IsConnected) : null;
                            if (helper != null)
                            {
                                try
                                {
                                    string content = CommonHelper.RemoveEnterString((helper as ScanHelper).GetBarcode());

                                    HWMessageBox.Show(this, $"结果：{content}");
                                }
                                catch (Exception ex)
                                {
                                    HWMessageBox.Show(this, $"发生异常：{ex.Message}");
                                }
                            }
                            else
                            {
                                Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                                try
                                {
                                    socket.ReceiveTimeout = 1000;
                                    socket.ConnectAsync(ip, port).Wait(500);

                                    if (socket.Connected)
                                    {
                                        socket.Send(Encoding.UTF8.GetBytes(cmdValue));
                                        byte[] buffer = new byte[1024];
                                        int length = socket.Receive(buffer);

                                        if (length > 0)
                                        {
                                            string content = Encoding.UTF8.GetString(buffer.Take(length).ToArray());

                                            HWMessageBox.Show(this, $"结果：{content}");
                                        }
                                        else
                                        {
                                            HWMessageBox.Show(this, "通讯异常");
                                        }
                                    }
                                    else
                                    {
                                        HWMessageBox.Show(this, "无法建立连接");
                                    }
                                }
                                catch (Exception ex)
                                {
                                    HWMessageBox.Show(this, $"发生异常：{ex.Message}");
                                }
                                finally
                                {
                                    if (socket != null && socket.Connected)
                                    {
                                        socket.Close();
                                        socket = null;
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        HWMessageBox.Show(this, "名称有误");
                    }
                }
                else
                {
                    HWMessageBox.Show(this, "信息不完整，无法进行功能触发");
                }
            }
            else
            {
                HWMessageBox.Show(this, "请先选中记录");
            }
            CommonHelper.CloseWaiting();
        }

        private void toolStripMenuItemSerialRead_Click(object sender, EventArgs e)
        {
            CommonHelper.ShowWaiting(this, "功能触发中，请稍候......");
            var cells = this.dataGridViewSerial.SelectedCells;
            if (cells != null && cells.Count > 0)
            {
                var row = this.dataGridViewSerial.Rows[cells[0].RowIndex];
                var tag = row.Tag as ScanComParam;
                if (tag != null)
                {
                    var name = tag.Remark;
                    if (!string.IsNullOrWhiteSpace(name))
                    {
                        var portName = tag.PortName;
                        var baudRate = tag.BaudRate;
                        var parity = tag.Parity;
                        var dataBit = tag.DataBits;
                        var stopBit = tag.StopBits;
                        var cmd = tag.Command;
                        cmd = cmd.Replace("\\r", "\r").Replace("\\n", "\n");
                        if (string.IsNullOrWhiteSpace(portName))
                        {
                            HWMessageBox.Show(this, $"串口有误");
                        }
                        else
                        {
                            if (string.IsNullOrWhiteSpace(cmd))
                            {
                                HWMessageBox.Show(this, "扫码命令有误");
                            }
                            else
                            {
                                string cmdValue = cmd.Replace("\\r", "\r").Replace("\\n", "\n");

                                var helper = APPInstance.HELPERS != null ?
                                    APPInstance.HELPERS.Find(v => v is ScanHelper
                                    && v.Name.Equals(name)
                                    && v.CommunicationType == ECommunicationType.SERIAL
                                    && v.IsConnected) : null;

                                if (helper != null)
                                {
                                    try
                                    {
                                        string content = CommonHelper.RemoveEnterString((helper as ScanHelper).GetBarcode());

                                        HWMessageBox.Show(this, $"结果：{content}");
                                    }
                                    catch (Exception ex)
                                    {
                                        HWMessageBox.Show(this, $"发生异常：{ex.Message}");
                                    }
                                }
                                else
                                {
                                    SerialPort serialPort = new SerialPort(portName, baudRate,
                                        CommonHelper.GetEnumByRealValue(parity, Parity.None), dataBit,
                                        CommonHelper.GetEnumByRealValue(stopBit, StopBits.One));
                                    try
                                    {
                                        serialPort.Open();
                                        serialPort.Write(cmdValue);
                                        int length = 0;
                                        for (var i = 0; i < 3; i++)
                                        {
                                            System.Threading.Thread.Sleep(1);
                                            length = serialPort.BytesToRead;
                                            if (length > 0)
                                            {
                                                break;
                                            }
                                            System.Threading.Thread.Sleep(1000);
                                        }
                                        if (length > 0)
                                        {
                                            byte[] buffer = new byte[length];
                                            serialPort.Read(buffer, 0, length);
                                            string content = Encoding.UTF8.GetString(buffer);

                                            HWMessageBox.Show(this, $"结果：{content}");
                                        }
                                        else
                                        {
                                            HWMessageBox.Show(this, "通讯异常");
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        HWMessageBox.Show(this, $"发生异常：{ex.Message}");
                                    }
                                    finally
                                    {
                                        if (serialPort != null && serialPort.IsOpen)
                                        {
                                            serialPort.Close();
                                            serialPort = null;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        HWMessageBox.Show(this, "名称有误");
                    }
                }
                else
                {
                    HWMessageBox.Show(this, $"信息不完整，无法触发功能");
                }
            }
            else
            {
                HWMessageBox.Show(this, "请先选中记录");
            }
            CommonHelper.CloseWaiting();
        }

        private void FormScan_Shown(object sender, EventArgs e)
        {
        }

        private void dataGridViewTcp_SelectionChanged(object sender, EventArgs e)
        {
            if (!this.mIsFirstTimeSelected)
            {
                SaveModules();

                int selectedRowIndex = this.dataGridViewTcp.SelectedCells == null || this.dataGridViewTcp.SelectedCells.Count == 0 ? -1 : this.dataGridViewTcp.SelectedCells[0].RowIndex;
                if (selectedRowIndex != -1)
                {
                    DataGridViewRow row = this.dataGridViewTcp.Rows[selectedRowIndex];
                    var name = CommonHelper.GetCellStringValue(row, "Name");
                    var ip = CommonHelper.GetCellStringValue(row, "TcpIP");
                    var port = CommonHelper.GetCellStringValue(row, "TcpPort");
                    var cmd = CommonHelper.GetCellStringValue(row, "Cmd");
                    cmd = cmd.Replace("\\r", "\r").Replace("\\n", "\n");

                    int portValue = 9004;
                    ScanTcpParam m = new ScanTcpParam()
                    {
                        Remark = name,
                        Command = cmd,
                        ServerIP = ip,
                        ServerPort = int.TryParse(port, out portValue) ? portValue : 9004,
                    };
                    if (row.Tag != null)
                    {
                        ScanTcpParam cm = row.Tag as ScanTcpParam;
                        m.PLCEntities = cm.PLCEntities;
                    }
                    row.Tag = m;

                    ShowModules(m.PLCEntities);

                    this.mSerialLastSelectedRowIndex = -1;
                    this.mTcpLastSelectedRowIndex = selectedRowIndex;
                }
            }
            this.mIsFirstTimeSelected = false;
        }

        private void dataGridViewRtu_SelectionChanged(object sender, EventArgs e)
        {
            if (!this.mIsFirstTimeSelected)
            {
                SaveModules();

                int selectedRowIndex = this.dataGridViewSerial.SelectedCells == null || this.dataGridViewSerial.SelectedCells.Count == 0 ? -1 : this.dataGridViewSerial.SelectedCells[0].RowIndex;
                if (selectedRowIndex != -1)
                {
                    DataGridViewRow row = this.dataGridViewSerial.Rows[selectedRowIndex];

                    var name = CommonHelper.GetCellStringValue(row, "Name");
                    var portName = CommonHelper.GetCellStringValue(row, "PortName");
                    var baudRate = CommonHelper.GetCellStringValue(row, "BaudRate");
                    var parity = CommonHelper.GetCellStringValue(row, "Parity");
                    var dataBit = CommonHelper.GetCellStringValue(row, "DataBit");
                    var stopBit = CommonHelper.GetCellStringValue(row, "StopBit");
                    var cmd = CommonHelper.GetCellStringValue(row, "Cmd");
                    cmd = cmd.Replace("\\r", "\r").Replace("\\n", "\n");

                    ScanComParam m = new ScanComParam()
                    {
                        Remark = name,
                        BaudRate = string.IsNullOrWhiteSpace(baudRate) ? 9600 : int.Parse(baudRate),
                        DataBits = string.IsNullOrWhiteSpace(dataBit) ? 9600 : int.Parse(dataBit),
                        Parity = string.IsNullOrWhiteSpace(parity) ? 9600 : int.Parse(parity),
                        StopBits = string.IsNullOrWhiteSpace(stopBit) ? 9600 : int.Parse(stopBit),
                        PortName = portName,
                        Command = cmd
                    };
                    if (row.Tag != null)
                    {
                        ScanComParam cm = row.Tag as ScanComParam;
                        m.PLCEntities = cm.PLCEntities;
                    }
                    row.Tag = m;

                    ShowModules(m.PLCEntities);

                    this.mTcpLastSelectedRowIndex = -1;
                    this.mSerialLastSelectedRowIndex = selectedRowIndex;
                }
            }
            this.mIsFirstTimeSelected = false;
        }
        private void SaveModules()
        {
            List<ScanPLCEntity> list = new List<ScanPLCEntity>();
            if (this.dataGridViewModules.Rows != null && this.dataGridViewModules.Rows.Count > 0)
            {
                foreach (DataGridViewRow row in this.dataGridViewModules.Rows)
                {
                    string trigger = CommonHelper.GetCellStringValue(row, "Trigger");
                    string barcode = CommonHelper.GetCellStringValue(row, "Barcode");
                    string time = CommonHelper.GetCellStringValue(row, "Time");
                    string result = CommonHelper.GetCellStringValue(row, "Result");
                    string done = CommonHelper.GetCellStringValue(row, "Done");
                    string mes = CommonHelper.GetCellStringValue(row, "Mes");
                    string remark = CommonHelper.GetCellStringValue(row, "Remark");

                    var p = new ScanPLCEntity()
                    {
                        TriggerAddress = trigger,
                        BarcodeAddress = barcode,
                        Remark = remark,
                        ResultDoneAddress = done,
                        ScanMESAddress = mes,
                        ScanResultAddress = result,
                        ScanTimeAddress = time,
                    };
                    if (!string.IsNullOrWhiteSpace(p.BarcodeAddress) && !string.IsNullOrWhiteSpace(p.TriggerAddress))
                    {
                        list.Add(p);
                    }
                }
            }
            if (this.mTcpLastSelectedRowIndex != -1)
            {
                var tcpRow = this.dataGridViewTcp.Rows[this.mTcpLastSelectedRowIndex];
                if (tcpRow != null && tcpRow.Tag != null)
                {
                    ScanTcpParam t = tcpRow.Tag as ScanTcpParam;
                    t.PLCEntities = list;
                    tcpRow.Tag = t;
                }
            }
            else if (this.mSerialLastSelectedRowIndex != -1)
            {
                var serialRow = this.dataGridViewSerial.Rows[this.mSerialLastSelectedRowIndex];
                if (serialRow != null && serialRow.Tag != null)
                {
                    ScanComParam t = serialRow.Tag as ScanComParam;
                    t.PLCEntities = list;
                    serialRow.Tag = t;
                }
            }
        }

        private void ShowModules(List<ScanPLCEntity> list)
        {
            this.dataGridViewModules.Rows.Clear();
            if (list != null && list.Count > 0)
            {
                foreach (var l in list)
                {
                    int index = this.dataGridViewModules.Rows.Add(1);
                    DataGridViewRow newRow = this.dataGridViewModules.Rows[index];

                    newRow.Cells["Trigger"].Value = l.TriggerAddress;
                    newRow.Cells["Barcode"].Value = l.BarcodeAddress;
                    newRow.Cells["Time"].Value = l.ScanTimeAddress;
                    newRow.Cells["Result"].Value = l.ScanResultAddress;
                    newRow.Cells["Done"].Value = l.ResultDoneAddress;
                    newRow.Cells["Mes"].Value = l.ScanMESAddress;
                    newRow.Cells["Remark"].Value = l.Remark;
                }
            }
        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            int index = tabControl1.SelectedIndex;

            if (index == 0)
            {
                this.dataGridViewTcp.Rows[0].Cells[0].Selected = true;
            }
            else if (index == 1)
            {
                this.dataGridViewSerial.Rows[0].Cells[0].Selected = true;
            }
        }

    }
}
